<template>
  <!-- 当 type 为 'select' 时，渲染 el-select -->
  <el-select
    v-if="type === 'select'"
    v-bind="$attrs"
    v-model="selectedValue"
    @change="handleChange"
    :loading="isLoading"
    :disabled="isDisabled"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    ></el-option>
  </el-select>

  <!-- 当 type 为 'radio' 时 -->
  <el-radio-group
    v-else-if="type === 'radio'"
    v-bind="$attrs"
    v-model="selectedValue"
    @change="handleChange"
    :disabled="isDisabled"
  >
    <el-radio v-for="item in options" :key="item.value" :value="item.value">
      {{ item.label }}
    </el-radio>
  </el-radio-group>

  <!-- 当 type 为 'radio-button' 时 -->
  <el-radio-group
    v-else-if="type === 'radio-button'"
    v-bind="$attrs"
    v-model="selectedValue"
    @change="handleChange"
    :disabled="isDisabled"
  >
    <el-radio-button
      v-for="item in options"
      :key="item.value"
      :value="item.value"
    >
      {{ item.label }}
    </el-radio-button>
  </el-radio-group>

  <!-- 当 type 为 'checkbox' 时 -->
  <el-checkbox-group
    v-else-if="type === 'checkbox'"
    v-bind="$attrs"
    v-model="selectedValue"
    @change="handleChange"
    :disabled="isDisabled"
  >
    <el-checkbox
      v-for="item in options"
      :value="item.value"
      :label="item.label"
    />
  </el-checkbox-group>

  <!-- 当 type 为 'checkbox-button' 时 -->
  <el-checkbox-group
    v-else-if="type === 'checkbox-button'"
    v-bind="$attrs"
    v-model="selectedValue"
    @change="handleChange"
    :disabled="isDisabled"
  >
    <el-checkbox-button
      v-for="item in options"
      :value="item.value"
      :label="item.label"
    />
  </el-checkbox-group>

  <!-- 可以添加一个默认情况或者错误提示，如果 type 不是 'select' 也不是 'radio' -->
  <div v-else>Unsupported type: {{ type }}</div>
</template>

<script setup>
import { ref, watch, computed, nextTick } from 'vue';
import { useDictStore } from '@/store';
import {
  ElSelect,
  ElOption,
  ElRadioGroup,
  ElRadio,
  ElRadioButton,
  ElCheckboxGroup,
  ElCheckbox,
} from 'element-plus';

const props = defineProps({
  code: {
    type: String,
    required: true,
  },
  perms: {
    type: Boolean,
    default: false,
  },
  modelValue: {
    // For v-model support
    type: [String, Number, Array, Boolean, Object],
    default: null,
  },
  // 新增 type 参数
  type: {
    type: String,
    default: 'select', // 默认值为 'select'
    validator: (value) =>
      [
        'select',
        'radio',
        'radio-button',
        'checkbox',
        'checkbox-button',
      ].includes(value),
  },
  // 新增 disabled 参数
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

const dictStore = useDictStore();
const options = ref([]);
const isLoading = ref(false);
const dataLoaded = ref(false);

// 计算属性：始终返回 modelValue，让 el-select/el-radio-group 自己处理数据加载前的显示
const selectedValue = computed({
  get() {
    // 否则复选框可能会点选不上
    if (props.type.startsWith('checkbox')) {
      // 如果 modelValue 不是数组 (比如是 null), 返回一个空数组
      return Array.isArray(props.modelValue) ? props.modelValue : [];
    }
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  },
});

// 计算属性：根据 props.disabled 和 isLoading 决定最终的禁用状态
const isDisabled = computed(() => {
  return props.disabled || isLoading.value;
});

const fetchDictionaryData = async () => {
  if (!props.code) return;

  isLoading.value = true;
  dataLoaded.value = false;

  try {
    const data = await dictStore.getDictionary(props.code, props.perms);
    options.value = data.map((item) => {
      const rawItemValue = item.value !== undefined ? item.value : item.id;
      let finalItemValue = rawItemValue;

      // 尝试根据 modelValue 的类型进行适配
      if (props.modelValue !== null && props.modelValue !== undefined) {
        let targetValueType;
        if (Array.isArray(props.modelValue) && props.modelValue.length > 0) {
          // 如果 modelValue 是数组，取第一个元素的类型作为目标类型
          targetValueType = typeof props.modelValue[0];
        } else if (!Array.isArray(props.modelValue)) {
          // 如果 modelValue 是单个值，取其类型作为目标类型
          targetValueType = typeof props.modelValue;
        }

        // 进行类型转换
        if (
          targetValueType === 'number' &&
          typeof rawItemValue === 'string' &&
          !isNaN(Number(rawItemValue))
        ) {
          finalItemValue = Number(rawItemValue);
        } else if (
          targetValueType === 'string' &&
          typeof rawItemValue === 'number'
        ) {
          finalItemValue = String(rawItemValue);
        }
        // 其他情况（如两者类型一致，或无法进行有效转换）则保持原样
      }

      return {
        label: item.label || item.name,
        value: finalItemValue,
      };
    });

    // 数据加载完成
    dataLoaded.value = true;

    // 确保在下一个tick中更新选中值，让el-select/el-radio-group能够正确回显
    await nextTick();
  } catch (error) {
    console.error('Failed to fetch dictionary data:', error);
    options.value = [];
    dataLoaded.value = true; // 即使出错也标记为已加载
  } finally {
    isLoading.value = false;
  }
};

// 监听 code 和 perms 变化，重新获取数据
watch([() => props.code, () => props.perms], fetchDictionaryData, {
  immediate: true,
});

const handleChange = (value, event) => {
  emit('update:modelValue', value);
  emit('change', value);
};

// 暴露一些有用的方法和属性
defineExpose({
  options,
  isLoading,
  dataLoaded,
  refresh: fetchDictionaryData,
});
</script>

<style scoped>
/* Add any specific styles for RaDictSelect here if needed */
</style>
